#include <iostream>
#include <vector>
#include "time.h"
#include "stdlib.h"

using namespace std;

#define MAX_ROW 6
#define MAX_COLUMN 8
#define MAX_SOLDIER_NUM 24

#define MAX_KIND_OF_SOLIDER 2

unsigned char GetOneKindOfSolider(unsigned char maxkind)
{
	return rand() % maxkind + 1;
}

unsigned char GetOneKindOfSoliderExcept(unsigned char maxkind, unsigned char exceptkind)
{
	if(maxkind = 1)
	{
		return 0;
	}

	unsigned char kind;
	while((kind = GetOneKindOfSolider(maxkind)) != exceptkind)
	{
		return kind;
	}
}

void InitBlocks(
				char* blocks
				, unsigned char row
				, unsigned char column
				, unsigned char maxsoldier
				, unsigned char maxkind
				)
{
	// error
	if(row <= 1 || column <= 1 || maxsoldier == 0)
	{
		return;
	}

	if(maxsoldier > row * column)
	{
		return;
	}

	// clear array
	for(unsigned int i = 0; i < (unsigned int)row * column; ++i)
	{
		blocks[i] = ' ';
	}

	// init array
	for(unsigned int i = 0; i < column; ++i)
	{
		unsigned char temp = GetOneKindOfSolider(maxkind);
		blocks[row * i] = temp;

		if((--maxsoldier == 0))
		{
			break;
		}
	
		int randnum = (maxsoldier + 1) < row ? (maxsoldier + 1) : row; 
		temp = rand() % randnum;

		for(unsigned int j = 0; j < unsigned int(row - 1); ++j)
		{
			if(j < temp)
			{
				blocks[row * i + j + 1] = GetOneKindOfSolider(maxkind);
			}
		}

		maxsoldier = maxsoldier - temp;
		if(maxsoldier == 0)
		{
			break;
		}
	}

	// left soldiers
	if(maxsoldier > 0)
	{
		for(unsigned int i = 0; i < (unsigned int)row * column; ++i)
		{
			if(blocks[i] == ' ')
			{
				blocks[i] = GetOneKindOfSolider(maxkind);
			}

			if(--maxsoldier == 0)
			{
				return;
			}
		}
	}
}

void DisplayBlocks(const char* blocks, unsigned char row, unsigned char column)
{
	for(unsigned int i = 0; i < row; ++i)
	{
		cout << "  ";

		for(unsigned int j = 0; j < column; ++j)
		{
			cout << blocks[j * row + i] << ' ';
		}

		cout << endl;
	}
}

int main()
{
	srand((unsigned int)time(NULL));

	char* blocks = new char[MAX_ROW * MAX_COLUMN];
	InitBlocks(blocks, MAX_ROW, MAX_COLUMN, MAX_SOLDIER_NUM, MAX_KIND_OF_SOLIDER);
	DisplayBlocks(blocks, MAX_ROW, MAX_COLUMN);

	printf("Press q to exit. \n");
	while(getchar() != 'q');

	delete blocks;
	blocks = 0;
}
